package com.ruicar.afs.cloud.afscase.message.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.afscase.message.condition.MessageTemplateCondition;
import com.ruicar.afs.cloud.afscase.message.entity.MessageTemplate;
import com.ruicar.afs.cloud.afscase.message.service.MessageTemplateService;
import com.ruicar.afs.cloud.afscase.message.vo.MsgTempVO;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.log.annotation.SysLog;
import com.ruicar.afs.cloud.common.core.query.QueryCondition;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.*;
import com.ruicar.afs.cloud.message.sendmessage.config.MessageConfig;
import com.ruicar.afs.cloud.message.sendmessage.dto.MessageDataDto;
import com.ruicar.afs.cloud.message.sendmessage.dto.SendMessageDto;
import com.ruicar.afs.cloud.message.sendmessage.dto.SendResultInfoDto;
import com.ruicar.afs.cloud.message.sendmessage.service.MessageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @description: 短信模板管理
 * @author jiaqi.guo
 * @created 2020/8/8 17:11
 * @version 1.0
 */
@Slf4j
@RestController
@AllArgsConstructor
@Api("短信模板")
@RequestMapping("/messageTemplate")

public class MessageTemplateController {
     private MessageTemplateService messageService;
     private MessageService service;
    private  final MessageConfig messageConfig;
    @PostMapping(value = "/queryTemplateList")
    @ApiOperation(value = "多条件分页获取信审短信模板信息数据")
    public IResponse<IPage<MessageTemplate>> queryTemplateList(@RequestBody QueryCondition<MessageTemplate> condition) {

        return IResponse.success(messageService.page(new Page(condition.getPageNumber(), condition.getPageSize()), Wrappers.<MessageTemplate>query().lambda()
                .eq(StringUtils.isNotBlank(condition.getCondition().getTemplateType()),MessageTemplate::getTemplateType,condition.getCondition().getTemplateType())
                .eq(StringUtils.isNotBlank(condition.getCondition().getStatus()),MessageTemplate::getStatus,condition.getCondition().getStatus())
                
        ));
    }

   

    @RequestMapping(value = "/deleteTemplate/{id}", method = RequestMethod.DELETE)
    @ApiOperation(value = "通过id删除")
    @Transactional
    @SysLog("删除短信模板")
    public IResponse<Boolean> deleteTemplate(@PathVariable String id) {
        MessageTemplate MessageTemplate = messageService.getById(id);
        if (MessageTemplate == null) {
            return new IResponse<Boolean>().setMsg("通过id删除数据成功");
        }
        messageService.removeById(id);
        return new IResponse<Boolean>().setMsg("通过id删除数据成功");
    }

    @PostMapping(value = "/addTemplate")
    @ApiOperation(value = "新增短信模板")
    @Transactional
    @SysLog("新增短信模板")
    public IResponse<Boolean> addTemplate(@RequestBody MessageTemplate template) {
        String templateId = template.getTemplateId();
        List<MessageTemplate> list = messageService.list(Wrappers.<MessageTemplate>query().lambda()
                .eq(MessageTemplate::getTemplateId, templateId));
        if (list != null && list.size() > 0) {
            return new IResponse<Boolean>().setMsg("模板ID:" + templateId + "重复,请重新提交！").setCode("0001");
        } else {
            messageService.save(template);
            return new IResponse<Boolean>().setMsg("新增短信模板成功");
        }
    }

    @PostMapping(value = "/editTemplate")
    @ApiOperation(value = "修改短信模板")
    @Transactional
    @SysLog("修改短信模板")
    public IResponse<Boolean> editTemplate(@RequestBody MessageTemplate MessageTemplate) {
        messageService.updateById(MessageTemplate);
        return new IResponse<Boolean>().setMsg("修改短信模板成功");
    }
    @PostMapping(value = "/sendMessageInfo")
    @ApiOperation(value = "短信发送接口")
    @Transactional
    @SysLog("短信发送")
    public IResponse<Boolean> sendMessageInfo(@RequestBody @Validated MessageTemplateCondition condition) {
        //查询生效模板
        MessageTemplate messageTemplate = messageService.getOne(Wrappers.<MessageTemplate>query().lambda()
                .eq(MessageTemplate::getTemplateType,condition.getTemplateType())
                .eq(MessageTemplate::getStatus,WhetherEnum.YES.getCode()));
        if (ObjectUtils.isNotEmpty(messageTemplate)) {
            MessageTemplate newMessageTemplate=  messageService.assemblyInformation(condition.getApplyNo(),condition.getName(),messageTemplate);
            if(ObjectUtils.isNotEmpty(newMessageTemplate)){
                return doSendMsg(newMessageTemplate,condition.getApplyNo(),condition.getPhone());
            }
        }else{
            throw new AfsBaseException("短信模板不存在！");

        }
        return   new IResponse<Boolean>().setMsg("短信发送成功！");
    }

    /**
    * @Description 根据模板类型获取转换后的模板
    * @Author Peng_Jinbo
    * @Date 2020/9/14 15:49
    */
    @GetMapping("/msgTemp")
    public IResponse getMsgTempByType(@ModelAttribute MessageTemplateCondition condition ){
        Assert.isTrue(StrUtil.isNotBlank(condition.getApplyNo()),"申请编号不可为空");
        Assert.isTrue(StrUtil.isNotBlank(condition.getTemplateType()),"短信模板类型不可为空");
        //查询生效模板
        MessageTemplate messageTemplate = messageService.getOne(Wrappers.<MessageTemplate>query().lambda()
                .eq(MessageTemplate::getTemplateType,condition.getTemplateType())
                .eq(MessageTemplate::getStatus,WhetherEnum.YES.getCode()));
        if(Objects.nonNull(messageTemplate)){
            return IResponse.success(messageService.assemblyInformation(condition.getApplyNo(),condition.getName(),messageTemplate));
        }
        return IResponse.fail("操作失败，当前短信模板不存在");
    }

    /**
    * @Description 发送短信
    * @Author Peng_Jinbo
    * @Date 2020/9/14 16:01
    */
    @PostMapping("/sendMsg")
    public IResponse sendMsg(@RequestBody MsgTempVO msgTemp){
        return doSendMsg(msgTemp,msgTemp.getApplyNo(),msgTemp.getPhone());
    }

    private IResponse doSendMsg(MessageTemplate messageTemplate,String applyNo,String phone){
        SendMessageDto messageDto= new SendMessageDto();
        messageDto.setChannel(messageTemplate.getChannel());
        messageDto.setCode(messageConfig.getCode());
        messageDto.setTimestamp(System.currentTimeMillis()/1000+"");
        messageDto.setUid(messageConfig.getUid());

        List<MessageDataDto> dataDtoList=new ArrayList<>();
        MessageDataDto dataDto= new MessageDataDto();
        dataDto.setDeptId(messageConfig.getDeptId());
        dataDto.setOrigin(messageConfig.getOrigin());
        dataDto.setPhone(phone);
        //estimatedTime不传默认当晚上23:59失效
        /*   dataDto.setEstimatedTime();*/
        //防重复-一天重复发
        SimpleDateFormat sd=new SimpleDateFormat("yyyyMMdd");
        dataDto.setSummaryId(applyNo+phone+sd.format(new Date()));
        dataDto.setSmsContent(messageTemplate.getTemplateContent());
        dataDto.setTemplateId(messageTemplate.getTemplateId());
        dataDto.setPriority(messageTemplate.getPriority());
        dataDtoList.add(dataDto);

        messageDto.setMessageDataDto(dataDtoList);
        SendResultInfoDto sendResultInfoDto=service.sendMessageData(messageDto);
        if(ObjectUtils.isNotEmpty(sendResultInfoDto)){
            if(sendResultInfoDto.getResult().equals(ResultBooleanEnum.TRUE.getCode())){
                return  new IResponse().setMsg("短信发送成功");
            }
            else{
                return new IResponse().setMsg("模板ID为:" + messageTemplate.getTemplateType() + "发送失败！原因:"+sendResultInfoDto.getMsgInfo()).setCode("0001");
            }
        }else{
            throw new AfsBaseException("短信接口响应失败！");
        }
    }
}